package com.web.base.open.dao;

import com.blue.jdbc.BaseDao;
import com.web.base.open.model.RoleUrl;
import com.web.base.open.model.Url;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开放平台角色-链接数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年02月27日
 */
@Repository("openRoleUrlDao")
public class RoleUrlDao extends BaseDao<RoleUrl>
{
	public RoleUrlDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, RoleUrl param)
	{
		if (param != null)
		{
			if (param.getRoleId() != null && param.getRoleId() > 0)
				sql.append(" and a.role_id=:roleId");
			
			if (param.getUrlId() != null && param.getUrlId() > 0)
				sql.append(" and a.url_id=:urlId");
			
		}
	}
	
	@Override
	protected StringBuilder select()
	{
		StringBuilder sql = new StringBuilder(64);
		sql.append("select a.*, u.url from open_role_url a");
		sql.append(" left join open_url u on u.id=a.url_id");
		sql.append(" where 1=1");
		return sql;
	}

	public void deleteByRole(Integer id)
	{
		String sql = "delete from open_role_url where role_id=?";
		jdbcTemplate.update(sql, id);
	}
	
	public List<String> listByRole(Integer roleId)
	{
		String sql = "select u.url from open_url u, open_role_url ru where u.id=ru.url_id and ru.role_id=?";
		List<String> list = jdbcTemplate.queryForList(sql, String.class, roleId);
		return list;
	}
	
	public List<Url> listSelect(Integer roleId)
	{
		Map<String, Object> param = new HashMap<>();
		param.put("roleId", roleId);
		String sql = "select m.id, m.parent_id, m.name, m.url, isnull(rm.role_id) `select` from open_url m"
				+ " left join (select * from open_role_url where role_id=:roleId) rm on rm.url_id=m.id"
				+ " where m.state=0 order by m.id";
		return jdbcObjectTemplate.list(Url.class, sql, param);
	}
	
}
